import Taro from "@tarojs/taro";
import { BaseApi, ClientOptions } from "./flora-api-base";

export type GuestUserInfo = { status: 'guest' }

export type UserInfo = {
  uid: number,
  email: string,
  name: string,
  is_dev: boolean,
};

export function createDzqApi(opts: { clientOptions: ClientOptions, base: BaseApi }) {
  const request = opts.base.request;
  // 接入应用认证
  async function getDzcToken(opts: { appId: string, secret: string }): Promise<{ status: 'ok', token: string } | { status: 'error', errorMsg: string }> {
    const r = await request<{ status: 'ok', token: string } | { status: 'error', errorMsg: string, subKind: string }>({
      // url: '/miniapp/account_login',
      url: 'https://esign.sigs.tsinghua.edu.cn/ecapi/token/sdkAccessToken',
      method: 'GET',
      data: {
        appId: opts.appId,
        secret: opts.secret
      },
      header: {
        // 暂不携带access token.
        Authorization: '',
      }
    });
    if ('data' in r) {
      if (r.data.message === 'success') {
        console.log('getDzcToken===========', r.data.data.accessToken);
        return { status: 'ok', token: r.data.data.accessToken };
      }
      return r.data;
    }
    console.log('login error:', r);
    return { status: 'error', errorMsg: '请求失败' };
  }


  //获取当前学生需要使用的模板
  async function getDzcMbList(opts: { token: string, ascription: string }): Promise<{ status: 'ok', templateId: string ,templateName:string} | { status: 'error', errorMsg: string }> {
    const r = await request<{ status: 'ok', templateId: string,templateName:string } | { status: 'error', errorMsg: string, subKind: string }>({
      // url: '/miniapp/account_login',
      url: 'https://esign.sigs.tsinghua.edu.cn/ecapi/interface/v1/template/search/bycurrentapp',
      method: 'GET',
      data: {
        // appId: opts.appId,
        // secret:opts.secret
      },
      header: {
        // 暂不携带access token.
        'X-Bjca-Token': opts.token
      }
    });
    if ('data' in r) {
      if (r.data.message === 'success') {
        var templateIds = "";
        var templateName = "";
        console.log('getDzcMbList==:', r.data.data.templates);
        var datate = r.data.data.templates;
        (datate || []).forEach((row: any) => {
          if (row.templateName.indexOf(opts.ascription) != -1) {
            templateIds = row.templateId;
            templateName=row.templateName;
          }
        })
        return { status: 'ok', templateId: templateIds,templateName:templateName };
      }
      return r.data;
    }
    console.log('login error:', r);
    return { status: 'error', errorMsg: '请求失败' };
  }



  //查询ToC签署流程
  async function getDzcQsLq(opts: { token: string }): Promise<{ status: 'ok', processId: string } | { status: 'error', errorMsg: string }> {
    console.log('r.data.data.templates==:', opts.token);
    const r = await request<{ status: 'ok', processId: string } | { status: 'error', errorMsg: string, subKind: string }>({
      // url: '/miniapp/account_login',
      url: 'https://esign.sigs.tsinghua.edu.cn/ecapi/interface/v1/process',
      method: 'GET',
      data: {
        // appId: opts.appId,
        // secret:opts.secret
      },
      header: {
        // 暂不携带access token.
        'X-Bjca-Token': opts.token
      }
    });
    if ('data' in r) {
      if (r.data.message === 'success') {
        console.log('getDzcQsLq==:', r.data);
        var processId = "";
        var datate = r.data.data.processSimpleResponses;
        (datate || []).forEach((row: any) => {
          if (row.processName.indexOf('入住协议签署流程') != -1) {
            processId = row.processId;
          }
        })
        return { status: 'ok', processId: processId };
      }
      return r.data;
    }
    console.log('login error:', r);
    return { status: 'error', errorMsg: '请求失败' };
  }


  //获取模板详情接口
  async function getMbdatail(opts: { token: string, templateId: string, processId: string,keyId:string,templateName:string}): Promise<{ status: 'ok', 'loginUrl': string, docId: string } | { status: 'error', errorMsg: string }> {
    console.log('templateId==:', opts.templateId);
    const r = await request<{ status: 'ok', loginUrl: string, docId: string } | { status: 'error', errorMsg: string, subKind: string }>({
      // url: '/miniapp/account_login',
      url: 'https://esign.sigs.tsinghua.edu.cn/ecapi/interface/v1/template/search/bytemplateid/' + opts.templateId,
      method: 'GET',
      data: {
        // appId: opts.appId,
        // secret:opts.secret
      },
      header: {
        // 暂不携带access token.
        'X-Bjca-Token': opts.token
      }
    });
    if ('data' in r) {
      if (r.data.message === 'success') {
        console.log('getMbdatail==:', r.data);
        var businessTypeId = r.data.data.businessTypeId;  //获取模板中自带的业务类型id
        const userInfo = Taro.getStorageSync('userInfo')
        console.log('userInfo==:', userInfo);
        var fieldValues=[]
        if (opts.templateName.indexOf('清华学院') != -1) {
          fieldValues=[
            {
              "fieldValue": userInfo.name,
              "fieldCode": "1547869756566315009",
            },
            {
              "fieldValue": userInfo.code,
              "fieldCode": "1551773087764357122",
            }, 
            {
              "fieldValue": userInfo.id_card,
              "fieldCode": "1551772917576278018",
            },
            {
              "fieldValue": userInfo.sex,
              "fieldCode": "1551773147289919489",
            },
            {
              "fieldValue": userInfo?.["dormitory_id.name"],
              "fieldCode": "1551775188309549057",
            }
          ]      
        }else if(opts.templateName.indexOf('大学城') != -1){
          fieldValues=[
            {
              "fieldValue": userInfo.name,
              "fieldCode": "1547869756566315009",  
            },
            {
              "fieldValue": userInfo?.["dormitory_id.name"],
              "fieldCode": "1551775188309549057",
            },
          
            {
              "fieldValue": userInfo.id_card,
              "fieldCode": "1551772917576278018",
            },
            {
              "fieldValue": userInfo.grade,
              "fieldCode": "1551830140767739906",  //哪一级
            },
            {
              "fieldValue": userInfo.bank_card_code,
              "fieldCode": "1551830703379095554",
            }
          ] 
        }
        var signatoryRoleCodeDate = r.data.data.webTemplatePresetData.signatorys
        var signatoryRoleCodeP = "";
        var signatoryRoleCodeR = "";
        (signatoryRoleCodeDate || []).forEach((row: any) => {
          if (row.signatoryRoleType.indexOf('PERSONAL') != -1) {
            signatoryRoleCodeP = row.signatoryRoleCode;
          } else {
            signatoryRoleCodeR = row.signatoryRoleCode;
          }
        })
        const rs = await request<{ status: 'ok', templateId: string } | { status: 'error', errorMsg: string, subKind: string }>({
          // url: '/miniapp/account_login',
          url: 'https://esign.sigs.tsinghua.edu.cn/ecapi/cus/assemble/openapi/v1/senddoc/sendB2CTemplate',
          method: 'POST',
          data: {
            "taskName": userInfo.code + "-住宿协议签署", //计划任务名称
            "sendReqId": opts.keyId,//调用方业务流水，必须唯一
            "processId": opts.processId,//签署流程id
            "businessType": businessTypeId, //业务类型id
            // senderName: userInfo.name, //发起人姓名
            // idCardNum: userInfo.id_card,//发起人证件号
            "sendOrgName": "清华大学深圳国际研究生院",       //发起机构名称可以不传 可以不传
            "unCreditCode": "222222222222222222",      //发起企业社会统一信用代码   可以不传
            // startTime: "222222222222222222", //签署开始时间   可以不传
            "endTime": "2022-09-05 00:00:00",            //签署截止时间 
            // "codeStatus": "DISABLE",    //是否添加二维码ENABLE-添加, DISABLE-不添加
            "exampleUploadType": "NAS",  //实例合同pdf下载方式(FTP、NAS、BASE64、SFTP、S3)默认NAS
            "templates": [
              {
                "templateId": opts.templateId,
                "relDocId": opts.keyId,
                "watermarkState": "DISABLE",
                "signatories": [
                  {
                    "signatoryRoleCode": signatoryRoleCodeR,
                    "signatoryType": "ENTERPRISE",
                    "signType": "SIGN",
                    "refuseState": "ENABLE",
                    "ownerType": " INSIDE",
                    // "autoSignState": "DISABLE",
                    "autoSignState": "ENABLE",
                    "enterpriseSignatory": {
                      "unCreditCode": "222222222222222222"
                    }
                  },
                  {
                    "signatoryRoleCode": signatoryRoleCodeP,
                    "signatoryType": "UN_REGISTER_USER",
                    "signType": "SIGN",
                    "refuseState": "ENABLE",
                    "ownerType": "OUTSIDE",
                    "autoSignState": "DISABLE"
                  }
                ]
              }
            ],         //签署方排序
            "importPersonInfos": [
              {
                "name": userInfo.name,
                "email": userInfo.email,
                "idCardNum": userInfo.id_card,
                "idCardType": "USER_IDCARD",
                "mobile": userInfo.phone,
                "fieldValues": fieldValues,

              }
            ],
            "signatoryOrders": [
              {
                "signatoryType": "UN_REGISTER_USER",
                "idCardNum": "XXXXXXXXXXXXXX",
                "orderNum": 1
              },
              {
                "signatoryType": "ENTERPRISE",
                "unCreditCode": "222222222222222222",
                "orderNum": 2
              }],// 导入用户集合
          },
          header:{
            // 暂不携带access token
            "X-Bjca-Token": opts.token
          }
        });
        if ('data' in rs) {
          console.log('rs====dzqfq:', rs);
          if (rs.data.message === 'success') {
            // console.log('rs.data.data.exampleDtos.loginUrl:', rs.data.data.exampleDtos[0].loginUrl);
            return {status: 'ok', loginUrl: rs.data.data.exampleDtos[0].loginUrl, docId: rs.data.data.exampleDtos[0].docId };
          }
          return r.data;
        }
      }
      return r.data;
    }
    console.log('login error:', r);
    return { status: 'error', errorMsg: '请求失败' };
  }
  return { getDzcToken, getDzcMbList, getDzcQsLq, getMbdatail };
};
